<script setup>
import { reactive, ref, onMounted } from "vue";
import { adminLogin } from "@/apis/admin/user";
import { useRouter } from "vue-router";
import axios from "axios";
import { ElMessage, ElMessageBox } from "element-plus";
const router = useRouter();
/**
 * 获取登陆表单的对象
 */
const loginFormRef = ref();
/**
 * 登陆表单数据
 */
const loginFormData = reactive({
  username: "admin",
  password: "123456QAZ",
  captcha: "1111", // 新增验证码字段
});

/**
 * 验证码图片Base64编码
 */
const captchaUrl = ref("");

/**
 * 刷新验证码
 */
const refreshCaptcha = () => {
  axios({
    method: "get",
    url: "http://localhost:8085/getCode", // 替换成实际的后端地址
    responseType: "arraybuffer", // 指定响应类型为二进制数据
  })
    .then((response) => {
      // 将二进制数据转换成Base64字符串
      const imageBase64 = btoa(
        new Uint8Array(response.data).reduce(
          (data, byte) => data + String.fromCharCode(byte),
          ""
        )
      );
      // 使用获取的验证码图片设置captchaUrl
      captchaUrl.value = `data:image/png;base64,${imageBase64}`;
    })
    .catch((error) => {
      console.error("Error fetching code:", error);
      ElMessage.error("获取验证码失败，请刷新页面重试");
    });
};

/**
 * 在组件挂载时加载验证码
 */
onMounted(() => {
  refreshCaptcha();
});

/**
 * 登录校验规则
 */
const loginFormRules = reactive({
  username: [
    { required: true, message: "用户名不能为空", trigger: "blur" },
    { min: 3, max: 25, message: "用户名长度为3~25", trigger: "blur" },
  ],
  password: [
    { required: true, message: "密码不能为空", trigger: "blur" },
    { min: 3, max: 25, message: "密码长度为3~25", trigger: "blur" },
  ],
  captcha: [
    { required: true, message: "验证码不能为空", trigger: "blur" },
    { min: 4, max: 6, message: "请输入正确的验证码", trigger: "blur" },
  ],
});

/**
 * 登陆提交函数
 */
const loginFormCommit = async () => {
  console.log(loginFormData);
  await loginFormRef.value.validate((valid) => {
    if (valid) {
      // 发请求
      adminLogin(loginFormData)
        .then((result) => {
          if (result.code === "00000") {
            console.log(result);
            sessionStorage.setItem("Authentication", result.data.token);
            router.push("/admin");
          } else {
            ElMessage.error(result.message || "登录失败");
            refreshCaptcha();
          }
        })
        .catch((error) => {
          // 登录失败时刷新验证码
          // ElMessage.error(error.message || "登录失败");
          refreshCaptcha();
        });
    } else {
      // 表单验证失败时也刷新验证码
      refreshCaptcha();
    }
  });
};
/**
 * 实现页面跳转
 * @param {*} path
 */
const navigateToPage = (path) => {
  // console.log(path);
  router.push(path);
};
</script>

<template>
  <div class="login-container">
    <div class="login-card">
      <div class="login-header">
        <h1>管理员登录</h1>
        <p class="subtitle">欢迎回来, 管理员</p>
      </div>

      <el-form
        class="login-form"
        label-width="auto"
        label-position="top"
        :model="loginFormData"
        :rules="loginFormRules"
        ref="loginFormRef"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="loginFormData.username"
            placeholder="请输入管理员用户名"
          />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
            type="password"
            v-model="loginFormData.password"
            placeholder="请输入密码"
          />
        </el-form-item>

        <!-- 新增验证码输入框和图片 -->
        <el-form-item label="验证码" prop="captcha">
          <div class="captcha-container">
            <el-input
              v-model="loginFormData.captcha"
              placeholder="请输入验证码"
              class="captcha-input"
            />
            <div class="captcha-image" @click="refreshCaptcha">
              <img v-if="captchaUrl" :src="captchaUrl" alt="验证码" />
              <div v-else class="loading-captcha">加载中...</div>
              <div class="refresh-tip">点击刷新</div>
            </div>
          </div>
        </el-form-item>

        <div class="form-footer">
          <el-button
            class="login-button"
            type="primary"
            @click="loginFormCommit"
          >
            登录
          </el-button>

          <el-button class="home-button" @click="navigateToPage('/')">
            返回首页
          </el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #1e1e1e 0%, #2d2d2d 100%);
  padding: 20px;
}

.login-card {
  width: 100%;
  max-width: 440px;
  background: rgba(255, 255, 255, 0.98);
  backdrop-filter: blur(20px);
  border-radius: 24px;
  padding: 40px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.2);
}

.login-header {
  text-align: center;
  margin-bottom: 40px;
}

.login-header h1 {
  font-size: 32px;
  font-weight: 600;
  color: #1d1d1f;
  margin-bottom: 8px;
  background: linear-gradient(45deg, #f56c6c, #e63946);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.subtitle {
  font-size: 16px;
  color: #86868b;
  letter-spacing: 0.5px;
}

.login-form {
  box-shadow: none;
  padding: 0;
}

.login-form :deep(.el-form-item__label) {
  font-size: 14px;
  font-weight: 500;
  color: #1d1d1f;
  padding-bottom: 8px;
}

.login-form :deep(.el-input__wrapper) {
  background: #f5f5f7;
  border: none;
  border-radius: 12px;
  padding: 12px 16px;
  box-shadow: none !important;
  transition: all 0.3s ease;
}

.login-form :deep(.el-input__wrapper:hover),
.login-form :deep(.el-input__wrapper.is-focus) {
  background: #ebebeb;
}

.login-form :deep(.el-input__inner) {
  font-size: 15px;
  color: #1d1d1f;
}

.login-form :deep(.el-input__inner::placeholder) {
  color: #86868b;
}

.form-footer {
  margin-top: 32px;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.login-button {
  width: 100%;
  height: 48px;
  font-size: 16px;
  font-weight: 500;
  background: linear-gradient(45deg, #f56c6c, #e63946);
  border: none;
  border-radius: 12px;
  transition: all 0.3s ease;
}

.login-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(229, 57, 53, 0.2);
}

.home-button {
  width: 100%;
  height: 48px;
  font-size: 16px;
  margin-left: 0;
  background: transparent;
  border: 2px solid #e4e4e4;
  color: #666;
  border-radius: 12px;
  transition: all 0.3s ease;
}

.home-button:hover {
  border-color: #f56c6c;
  color: #f56c6c;
}

@media (max-width: 480px) {
  .login-card {
    padding: 32px 24px;
  }

  .captcha-container {
    flex-direction: column;
    align-items: stretch;
  }

  .captcha-image {
    width: 100%;
  }
}

/* 验证码相关样式 */
.captcha-container {
  display: flex;
  align-items: center;
  gap: 12px;
}

.captcha-input {
  flex: 1;
}

.captcha-image {
  width: 120px;
  height: 44px;
  cursor: pointer;
  position: relative;
  border-radius: 8px;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f5f7;
  border: 1px solid #e4e4e7;
}

.loading-captcha {
  font-size: 12px;
  color: #86868b;
}

.captcha-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.refresh-tip {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.3);
  color: white;
  font-size: 12px;
  padding: 2px 0;
  text-align: center;
  opacity: 0;
  transition: opacity 0.3s;
}

.captcha-image:hover .refresh-tip {
  opacity: 1;
}
</style>
